﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace MvcTemplates
{
    public class HtmlAttributesAttribute : MetadataAttribute
    {
        public HtmlAttributesAttribute( string[] names, string[] values )
        {
            HtmlAttributeNames = names;
            HtmlAttributeValues = values;
        }

        protected HtmlAttributesAttribute(){}

        public string[] HtmlAttributeNames { get; set; }
        public string[] HtmlAttributeValues { get; set; }

        public string GetIdOrNull()
        {
            if ( HtmlAttributeNames == null )
                return null;

            var index = Array.FindIndex( HtmlAttributeNames, x => x.Equals( "id", StringComparison.OrdinalIgnoreCase ) );
            if ( index >= 0 )
            {
                var value = HtmlAttributeValues.ElementAtOrDefault( index );
                if ( value == null )
                {
                    throw GetIndexOutOfRangeException( HtmlAttributeNames[index] );
                }
                return value;
            }

            return null;
        }

        private IndexOutOfRangeException GetIndexOutOfRangeException( string attributeName )
        {
            return new IndexOutOfRangeException(
                        "There was no value found for the AttributeName: " + attributeName +
                        "\nYou must specify an AttributeValue for each AttributeName you provide."                            
                        );
        }

        public virtual void ModifyHtmlAttributes( IDictionary<string, object> htmlAttributes )
        {
            if ( HtmlAttributeNames == null || HtmlAttributeValues == null )
                return;

            if ( htmlAttributes == null )
                htmlAttributes = new Dictionary<string, object>();

            HtmlAttributeValues = HtmlAttributeValues.Select( x => x.ToLower() ).ToArray();

            var newAttributes = new Dictionary<string, object>();

            for ( int i = 0; i < HtmlAttributeNames.Length; i++ )
            {
                var value = HtmlAttributeValues.ElementAtOrDefault( i );
                if ( value == null )
                {
                    throw GetIndexOutOfRangeException( HtmlAttributeNames[i] );
                }

                newAttributes[HtmlAttributeNames[i]] = value;
            }

            TemplateHelpers.MergeAttributes( newAttributes, htmlAttributes );
        }
    }
}